<?php
namespace control;
/*
*利润表季报类
*/

class profitQuarterlyClass extends adIndexClass
{
    private const page = 'profitQuarterly';
    private const title = '利润表季报';
    private const table = 'profit_income';

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "会计期间" => componentClass::quarterSelect(['name'=>'month','value'=>componentClass::quarter_date_format($this->date)]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        //控件
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= "<span class='spanButton'  onclick=\"window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage')\">打印</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }


    /*客户列表-查询结果*/
    public function homeSearch()
    {
        $accountRule = companyClass::returnRule(1);
        $assetObj = new assetDebtClass();
        $month =componentClass::textToMonth($this->post('month'))?:date('Y-m');

        $startMonth = date('Y', strtotime($month . '-01')) . '-' . sprintf('%02d', (ceil(date('n', strtotime($month . '-01')) / 3) - 1) * 3 + 1);
        $endMonth = date('Y', strtotime($month . '-01')) . '-' . sprintf('%02d', (ceil(date('n', strtotime($month . '-01')) / 3) - 1) * 3 + 3);
        static::rSet(self::$stid . self::page . 'Month', $month);

        // 月份选择器
        $monthSelector = componentClass::monthSelector(implode('~',[$startMonth,$endMonth]));
        $tr[] = array('项目', '行次', "本年累计金额", '本季度金额'.$monthSelector['button']);
        if($accountRule =='enterpriseRule'){
            $all = find(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and pid = '' order by list"));
            $list = 0;
            foreach ($all['array'] as $array) {
                if (!in_array($array['name'], ['营业利润', '利润总额', '净利润','其他综合收益的税后净额','综合收益总额'])) {
                    $result = $this->balance($array['name'], $startMonth, $endMonth);
                } else {
                    $result = $this->totalProfit($array['name'], $startMonth, $endMonth);
                }
                $list++;
                $tr[] = ["<span style='font-weight: bold'>{$array['title']}</span>", $list, $assetObj->fontColor($result['balance']), $assetObj->fontColor($result['monthBalance'])];
                $res = $this->loopTr($array['name'], $list, $startMonth, $endMonth, $assetObj);
                $tr = array_merge($tr, $res);
            }
        }elseif($accountRule =='smallEnterpriseRule'){
            $all = find(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and pid = '' order by list"));
            $list = 0;
            foreach ($all['array'] as $array) {
                if (!in_array($array['name'], ['营业利润', '利润总额', '净利润'])) {
                    $result = $this->balance($array['name'], $startMonth, $endMonth);
                } else {
                    $result = $this->totalProfit($array['name'], $startMonth, $endMonth);
                }
                $list++;
                $tr[] = ["<span style='font-weight: bold'>{$array['title']}</span>", $list, $assetObj->fontColor($result['balance']), $assetObj->fontColor($result['monthBalance'])];
                $res = $this->loopTr($array['name'], $list, $startMonth, $endMonth, $assetObj);
                $tr = array_merge($tr, $res);
            }
        }

        $assetObj = new assetDebtClass();
        //返回
        $json['html'] =
            "<div class='acct-main-container'>
                <form name='listForm'>" .
                    $this->tableMany(array("tr" => $tr,"displayFields" => false)) .
                "</form>" .
                $monthSelector['html'].
            "</div>" .
            $this->css() .
            $assetObj->tableCss() .
            clear;
        return json_encode($json, 320);
    }


    public function totalProfit($name, $month, $endMonth): array
    {
        $money = $monthMoney = 0;
        $accountRule = companyClass::returnRule(1);
        if ($name == '营业利润') {
            $result = $this->balance('营业收入', $month, $endMonth);
            $all = find(array('table' => self::table, 'where' => "pid = '营业收入' and coid = '" . self::$coid . "'"));
            $money = $result['balance'];
            $monthMoney = $result['monthBalance'];
            if ($accountRule =='enterpriseRule'){
                foreach ($all['array'] as $array) {
                    $result = $this->balance($array['name'], $month, $endMonth);
                    if (in_array($array['name'],['投资收益','公允价值变动收益'])) {
                        $money += $result['balance'];
                        $monthMoney += $result['monthBalance'];
                    } else {
                        $money -= $result['balance'];
                        $monthMoney -= $result['monthBalance'];
                    }
                }
            }elseif($accountRule =='smallEnterpriseRule'){
                foreach ($all['array'] as $array) {
                    $result = $this->balance($array['name'], $month, $endMonth);
                    if ($array['name'] == '投资收益') {
                        $money += $result['balance'];
                        $monthMoney += $result['monthBalance'];
                    } else {
                        $money -= $result['balance'];
                        $monthMoney -= $result['monthBalance'];
                    }
                }
            }

        } elseif ($name == '利润总额') {
            $result = $this->totalProfit('营业利润', $month, $endMonth);
            $money = $result['balance'];
            $monthMoney = $result['monthBalance'];
            $all = find(array('table' => self::table, 'where' => "pid = '营业利润' and coid = '" . self::$coid . "'"));
            if ($accountRule =='enterpriseRule'){
                foreach ($all['array'] as $array) {
                    $result = $this->balance($array['name'], $month, $endMonth);
                    if (in_array($array['name'], ['营业外收入'])) {
                        $money += $result['balance'];
                        $monthMoney += $result['monthBalance'];
                    } else {
                        $money -= $result['balance'];
                        $monthMoney -= $result['monthBalance'];
                    }
                }
            }elseif($accountRule =='smallEnterpriseRule'){
                foreach ($all['array'] as $array) {
                    $result = $this->balance($array['name'], $month, $endMonth);
                    if (in_array($array['name'], ['营业外收入', '政府补助'])) {
                        $money += $result['balance'];
                        $monthMoney += $result['monthBalance'];
                    } else {
                        $money -= $result['balance'];
                        $monthMoney -= $result['monthBalance'];
                    }
                }
            }

        } elseif ($name == '净利润') {
            $result = $this->totalProfit('利润总额', $month, $endMonth);
            $money = $result['balance'];
            $monthMoney = $result['monthBalance'];
            $all = find(array('table' => self::table, 'where' => "pid = '利润总额' and coid = '" . self::$coid . "'"));
            foreach ($all['array'] as $array) {
                $result = $this->balance($array['name'], $month, $endMonth);
                $money -= $result['balance'];
                $monthMoney -= $result['monthBalance'];
            }
        }elseif($name == '其他综合收益的税后净额'){
            $money = 0;
            $monthMoney = 0;
        }elseif($name =='综合收益总额'){
            $result = $this->totalProfit('净利润', $month,$endMonth);
            $money = $result['balance'];
            $monthMoney = $result['monthBalance'];
        }
        return ['balance' => $money, 'monthBalance' => $monthMoney];
    }



    private function loopTr($pid, &$list, $month, $endMonth, $assetObj, $isExport = false): array
    {
        $tr = [];
        $all = find(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and pid = '$pid' order by list"));
        foreach ($all['array'] as $array) {
            $list++;
            $result = $this->balance($array['name'], $month, $endMonth);
            if (!in_array($array['pid'], ['营业利润', '利润总额', '营业收入','其他综合收益的税后净额','综合收益总额'])) {
                $title = "&emsp;&emsp;" . $array['title'];
                if ($isExport) {
                    $title = "    " . $array['title'];
                }
            } else {
                $title = "&emsp;" . $array['title'];
                if ($isExport) {
                    $title = "  " . $array['title'];
                }
            }

            $tr[] = [$title, $list, $assetObj->fontColor($result['balance']), $assetObj->fontColor($result['monthBalance'])];
            $res = $this->loopTr($array['name'], $list, $month, $endMonth, $assetObj, $isExport);
            $tr = array_merge($tr, $res);
        }
        return $tr;
    }

    private function css()
    {
        return <<<eof
<style>
.tableMany{
  table-layout: fixed;
}
</style>
eof;

    }

    /**
     * 期末余额
     */
    public function balance($name, $month, $endMonth = '')
    {
        $all = find(array('table' => 'profit_income_formula', 'where' => "name = '$name' and coid = '" . self::$coid . "'"));
        $grandTotalBalance = 0;//本年累计余额
        $monthBalance = 0;//本季度金额
        $multObj = new multiColumnAccountClass();
        foreach ($all['array'] as $array) {
            $childGrandTotalBalance = 0;
            $childMonthBalance = 0;
            $columns=[];
            $multObj->loopSubjectIds($array['subjectId'], $columns);
            foreach ($columns as $subjectId){
                //本年累计
                $childGrandTotalBalance +=  $this->yearMoney($subjectId, $month, $array['rule']);
                $childMonthBalance +=  $this->monthMoney($subjectId, $month, $endMonth, $array['rule']);
            }
            $grandTotalBalance = match ($array['symbol']) {
                '-' => $grandTotalBalance - $childGrandTotalBalance,
                default => $grandTotalBalance + $childGrandTotalBalance
            };
            $monthBalance = match ($array['symbol']) {
                '-' => $monthBalance - $childMonthBalance,
                default => $monthBalance + $childMonthBalance
            };
        }
        return ['balance' => $grandTotalBalance, 'monthBalance' => $monthBalance];
    }

    /**
     * 本年累计
     */
    public function yearMoney($subjectId, $month, $rule): float|int
    {
        $subjectBalance = new subjectBalanceClass();
        $company = query('company', "coid = '" . self::$coid . "'");
        $subject = query('subject', "id = '$subjectId'");
        $year = date('Y', strtotime($month . '-01'));
        $where = " and date_format(a.recordDate,'%Y') >= '$year' and date_format(a.recordDate,'%Y-%m') <= '$month'";
        $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and a.source !='期末结转'" . $where.voucherClass::joinWhere()));
        $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and a.source !='期末结转'" . $where.voucherClass::joinWhere()));
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        switch ($rule) {
            case '贷方发生额':
                $balance = $daiInit['money'];
                break;
            case '借方发生额':
                $balance = $jieInit['money'];
                break;
            case '期初余额':
                $initResult = $subjectBalance->initMoney($subject, $year . '-01-01');
                $balance = $initResult['jieMoney']?:$initResult['daiMoney'];
                break;
            default://发生额
                if ($subject['direction'] =='借'){
                    $balance=$jieInit['money']-$daiInit['money'];
                }else{
                    $balance=$daiInit['money']-$jieInit['money'];
                }
                break;
        }
        if ($year <= date('Y', strtotime($company['startDate'] . '-01'))) {
            switch ($rule) {
                case '贷方发生额':
                    $balance += self::centToYuan($subject['loanMoney']);
                    break;
                case '借方发生额':
                    $balance += self::centToYuan($subject['borrowMoney']);
                    break;
                case '期初余额':
                    $initResult = $subjectBalance->initMoney($subject, $company['startDate'] . '-01');
                    $balance += $initResult['jieMoney']?:$initResult['daiMoney'];
                    break;
                default://发生额
                    if ($subject['direction'] =='借'){
                        $balance +=self::centToYuan($subject['borrowMoney'])-self::centToYuan($subject['loanMoney']);
                    }else{
                        $balance +=self::centToYuan($subject['loanMoney'])-self::centToYuan($subject['borrowMoney']);
                    }
                    break;
            }
        }
        return $balance;
    }

    /**
     * 本季度金额
     */
    public function monthMoney($subjectId, $startMonth, $endMonth, $rule): float|int
    {
        test($startMonth.'==='.$endMonth);
        $where = " and date_format(a.recordDate,'%Y-%m') >= '$startMonth' and date_format(a.recordDate,'%Y-%m') <= '$endMonth' and b.subjectId = '$subjectId'";
        $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.direction = '借' and a.source !='期末结转'" . $where.voucherClass::joinWhere()));
        $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.direction = '贷' and a.source !='期末结转'" . $where.voucherClass::joinWhere()));
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        $subject = query('subject',"id = '$subjectId'");
        switch ($rule) {
            case '贷方发生额':
                $balance = $daiInit['money'];
                break;
            case '借方发生额':
                $balance =$jieInit['money'];
                break;
            case '期初余额':
                $subjectBalance = new subjectBalanceClass();
                $subject = query('subject',"id = '$subjectId'");
                $initResult = $subjectBalance->initMoney($subject, $startMonth);
                $balance = $initResult['jieMoney']?:$initResult['daiMoney'];
                break;
            default://发生额
                if ($subject['direction'] =='借'){
                    $balance=$jieInit['money']-$daiInit['money'];
                }else{
                    $balance=$daiInit['money']-$jieInit['money'];
                }
                break;
        }
        return $balance;
    }

    public function printPage(): string
    {
        $month = static::rGet(self::$stid . self::page . 'Month');
        $year = date('Y年',strtotime($month.'-01'));
        $reason = (ceil(date('n', strtotime($month . '-01')) / 3));
        $reason = $year.'第'. $reason.'季度';
        $startMonth = date('Y', strtotime($month . '-01')) . '-' . sprintf('%02d', (ceil(date('n', strtotime($month . '-01')) / 3) - 1) * 3 + 1);
        $endMonth = date('Y', strtotime($month . '-01')) . '-' . sprintf('%02d', (ceil(date('n', strtotime($month . '-01')) / 3) - 1) * 3 + 3);
        $company = query('company', "coid = '" . self::$coid . "'");//公司名称
        $tr = [];
        $all = find(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and pid = '' order by list"));
        $list = 0;
        $assetObj = new assetDebtClass();
        foreach ($all['array'] as $array) {
            $list++;
            if (!in_array($array['name'], ['营业利润', '利润总额', '净利润','其他综合收益的税后净额','综合收益总额'])) {
                $result = $this->balance($array['name'], $startMonth, $endMonth);
            } else {
                $result = $this->totalProfit($array['name'], $startMonth, $endMonth);
            }
            $tr[] = ["<span style='font-weight: bold'>{$array['title']}</span>", $list, $assetObj->fontColor($result['balance']), $assetObj->fontColor($result['monthBalance'])];

            $res = $this->loopTr($array['name'], $list, $startMonth, $endMonth,$assetObj);
            $tr = array_merge($tr, $res);
        }

        $tempHtml = '';
        foreach ($tr as $array) {
            $tempHtml .= "<tr class='have_border'>";
            for ($i = 0; $i <= 3; $i++) {
                $tempHtml .= "<td>{$array[$i]}</td>";
            }
            $tempHtml .= "</tr>";
        }

        $divHtml = "
                 <div>
                      <div class='printTitle' style='font-weight: bold'>利润表季报</div>
                 </div>
                 <div class='table-top-title'><div style='flex: 1'>编制单位：$company[name]</div><div style='flex: 1;text-align: center'>$reason</div><div style='flex: 1;text-align: right'>单位：元</div></div>
              <table class='printTable' style='font-size: 13px'  data-op-type='block-box'>
                <tbody class='nop-fill-box'>
               <tr class='have_border'>
                   <td>项目</td>
                   <td>行次</td>
                   <td>本年累计金额</td>
                   <td>本季度金额</td>
                </tr>
                $tempHtml
               </tbody>
              </table>
            ";
        $html = <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       $divHtml
                    </div>
                  <style>
                      .footer-ul-parent{float: right;margin-right: 10px}
                      .footer-ul li{margin-top: 10px}
                      .table-top-title{
                        height: 30px;
                        line-height: 30px;
                        font-size: 14px;
                        margin-top: 20px;
                        display: flex;
                        flex-direction: row;
                        justify-content: space-between;
                      }
</style>
eof;
        $print = new printClass();

        return $print->showPrint($html, 'portrait', ['padding' => "5mm 10mm 5mm 10mm"]);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr = [];
            $month = static::rGet(self::$stid . self::page . 'Month');
            $startMonth = date('Y', strtotime($month . '-01')) . '-' . sprintf('%02d', (ceil(date('n', strtotime($month . '-01')) / 3) - 1) * 3 + 1);
            $endMonth = date('Y', strtotime($month . '-01')) . '-' . sprintf('%02d', (ceil(date('n', strtotime($month . '-01')) / 3) - 1) * 3 + 3);
            $title = array('资产', '行次', "期末余额", '年初余额', '负债和所有者权益', '行次', "期末余额", '年初余额');
            $all = find(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and pid = '' order by list"));
            $list = 0;
            foreach ($all['array'] as $array) {
                $list++;
                if (!in_array($array['name'], ['营业利润', '利润总额', '净利润','其他综合收益的税后净额','综合收益总额'])) {
                    $result = $this->balance($array['name'], $startMonth, $endMonth);
                } else {
                    $result = $this->totalProfit($array['name'], $startMonth, $endMonth);
                }
                $tr[] = [$array['title'], $list, $result['balance'], $result['monthBalance']];
                $res = $this->loopTr($array['name'], $list, $startMonth, $endMonth, true);
                $tr = array_merge($tr, $res);
            }
            $text = $this->control['name'] . "导出了资产负债表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, "资产负债表.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

}

